﻿using BLL;
using Model;
using System;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Print
{
    public partial class UrgentSumPrint : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string userName = "";
            if (HttpContext.Current.Session["SysUserInfo"] != null)
            {
                userName = ((Sys_User)Session["SysUserInfo"]).USER_NAME.ToString();
                if (!IsPostBack)
                {
                    string companyid = Request.QueryString["cid"].ToString();
                    string startTime = Request.QueryString["timestart"].ToString();
                    string entTime = Request.QueryString["timeEnd"].ToString();
                    StringBuilder sb = new StringBuilder();

                    if (companyid != "")
                    {
                        sb.AppendFormat(" and  c.cmy_id in({0})", companyid);
                    }
                    if (startTime == "" && entTime == "")
                    {
                        BindData(sb.ToString());
                    }
                    else
                    {
                        if (startTime == "")
                        {
                            startTime = "1900-01-01";
                        }

                        if (entTime == "")
                        {
                            entTime = DateTime.Now.ToString("yyyy-MM-dd");
                        }

                        sb.AppendFormat(" and trunc(u.applydate) between to_date('{0}','yyyy-MM-dd') and to_date('{1}','yyyy-MM-dd')", startTime, entTime);
                        BindData(sb.ToString());
                    }
                }
            }
            else
            {
                MessageBox.ResponseScript(this, "alert('【系统提示】对不起，您的登录已过期，请重新登录！');window.close();");
            }
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="companyid"></param>

        #region 读取数据

        ///
        public void BindData(string sqlWhere)
        {
            string sql = string.Format(@"select  c.cmy_id, c.cmy_name names,sum(u.applymoney)||'元' appmoney,sum(u.realmoney)||'元' remoney,sum(u.realmoney) remoneys
                              from qs_urgentapply u,sys_company c
                            where u.companyid=c.cmy_id {0}
                            group by c.cmy_name  ,c.cmy_id
                            having 1=1

                             union all
                             select null,'合计', sum(u.applymoney)||'元' appmoney ,sum(u.realmoney)||'元' remoney ,sum(u.realmoney) remoneys
                             from qs_urgentapply u,sys_company c
                            where u.companyid=c.cmy_id {1}
                            group by null  ,null
                            having 1=1  ", sqlWhere, sqlWhere);

            DataTable dt = new BaseBLL().Query(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                DrawData(dt);
            }
        }

        #endregion 读取数据

        public void DrawData(DataTable dtA)
        {
            int allCount = dtA.Rows.Count;
            int pageCount = 30; //int.Parse(ConfigurationManager.AppSettings["HReportRow"].ToString()); ;//每一页显示的行数

            string companyName = "";
            string sqlCompany = "select c.cmy_name from sys_company  c where c.cmy_id=" + ((Model.Sys_User)(Session["SysUserInfo"])).USER_COMPANY;
            DataTable dt = new BaseBLL().Query(sqlCompany);
            if (dt != null || dt.Rows.Count > 0)
            {
                companyName = dt.Rows[0][0].ToString();
            }

            string nowdate = DateTime.Now.ToString("yyyy年MM月dd日");
            //下面4行分别声明要打印的表、表头、表体、表尾
            HtmlGenericControl ht = null;
            HtmlGenericControl myThead = null;
            HtmlGenericControl myTbody = null;
            HtmlGenericControl myTfoot = null;
            HtmlGenericControl myTable = null;

            HtmlTableRow row = null;
            HtmlTableCell cell = null;

            Table tb = new Table();
            tb.Width = Unit.Percentage(100);
            TableRow tr = new TableRow();
            TableCell td = new TableCell();
            td.VerticalAlign = VerticalAlign.Top;
            td.BorderStyle = BorderStyle.None;
            td.HorizontalAlign = HorizontalAlign.Center;
            myTable = CreateHTMLMainTable("95%", "border-collapse:collapse;border:2px;", string.Empty);
            myThead = new HtmlGenericControl("thead");
            myThead.Attributes.Add("style", "display:table-header-group;font-weight:bold");
            myTbody = new HtmlGenericControl("tbody");
            myTfoot = new HtmlGenericControl("tfoot");
            myTfoot.Attributes.Add("style", "display:table-footer-group;font-weight:bold");
            myTable.Controls.Add(myThead);
            myTable.Controls.Add(myTbody);
            myTable.Controls.Add(myTfoot);
            td.Controls.Add(myTable);
            tr.Controls.Add(td);
            tb.Controls.Add(tr);
            form1.Controls.Add(tb);

            ht = CreateHTMLMainTable("100%", "border-top-width:0px", string.Empty);//创建一个Table作为表体

            int length = allCount / pageCount;
            if (allCount % pageCount != 0)
            {
                length++;
            }

            int i = 1;
            for (i = 1; i <= length; i++)
            {
                if (i != length)
                {
                    ht = FillDataToHtmlHeadTable(companyName, nowdate);
                    DataTable dtList = GetListDataOfOnePage(dtA, pageCount, i);

                    ht = FillDataToHtmlTable(dtList, ht, "td_tableData");//插入数据行

                    row = CreateHTMLRow("30px", null, "tr_pageHead");

                    string userName = ((Sys_User)Session["SysUserInfo"]).USER_NAME.ToString();
                    row.Cells.Add(CreateHTMLCell("制表人：" + userName, ";font-size:10pt", "left", null, 2));

                    row.Cells.Add(CreateHTMLCell("打印日期：" + nowdate, "font-size:10pt", "right", null, 2));
                    ht.Controls.Add(row);

                    FillTableToTbody(ht, ref myTbody, allCount, pageCount, i);
                }
                else
                {
                    ht = FillDataToHtmlHeadTable(companyName, nowdate);
                    DataTable dtList = GetListDataOfOnePage(dtA, pageCount, i);

                    ht = FillDataToHtmlTable(dtList, ht, "td_tableData");//插入数据行
                    ht = FillEmptyDataToHtmlTable(pageCount - dtList.Rows.Count, ht, "td_tableData");//插入空行

                    row = CreateHTMLRow("30px", null, "tr_pageHead");

                    string userName = ((Sys_User)Session["SysUserInfo"]).USER_NAME.ToString();
                    row.Cells.Add(CreateHTMLCell("制表人：" + userName, "font-size:10pt", "left", null, 2));

                    row.Cells.Add(CreateHTMLCell("打印日期：" + nowdate, "font-size:10pt", "right", null, 2));
                    ht.Controls.Add(row);

                    FillTableToTbody(ht, ref myTbody, allCount, pageCount, i);
                }
            }
        }

        #region 添加数据

        /// <summary>
        /// 添加数据到表头
        /// </summary>
        /// <param name="dtHead"></param>
        /// <param name="projectType"></param>
        /// <param name="companyName"></param>
        /// <param name="currentPage"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private HtmlGenericControl FillDataToHtmlHeadTable(string companyName, string nowdate)
        {
            HtmlTableRow row = null;
            HtmlGenericControl ht = null;

            ht = CreateHTMLMainTable("100%", "border-bottom-width:0px", "");//td_table

            row = CreateHTMLRow("50px", null, "tr_pageHead");
            row.Cells.Add(CreateHTMLCell("<strong>紧&nbsp;急&nbsp;资&nbsp;金&nbsp;统&nbsp;计</strong>", "font-size:20pt;width:100%", "center", null, 6));
            ht.Controls.Add(row);

            row = CreateHTMLRow(null, null, "tr_pageHead");
            ht.Controls.Add(row);

            row = CreateHTMLRow(null, "border:0px solid; border-color:black;", "tr_pageHead");
            row.Cells.Add(CreateHTMLCell("编制单位：" + companyName, "font-size:12pt;border-color:black;", "left", null, 3));
            row.Cells.Add(CreateHTMLCell("单位：元", "font-size:12pt;border-color:black;", "right", null, 1));
            ht.Controls.Add(row);

            row = CreateHTMLRow("", null, "");
            row.Cells.Add(CreateHTMLCell("<strong>编号</strong>", "width:17%;border-left-width:2px;border-top-width:2px;border:1px solid;", "center", "td_tableData", 1));
            row.Cells.Add(CreateHTMLCell("<strong>公司名称</strong>", "width:34%;border-top-width:2px;border:1px solid;", "center", "td_tableData", 1));
            row.Cells.Add(CreateHTMLCell("<strong>申请金额</strong>", "width:27%;border-top-width:2px;border:1px solid;", "center", "td_tableData", 1));
            row.Cells.Add(CreateHTMLCell("<strong>实际金额</strong>", "width:27%;border-top-width:2px;border:1px solid;", "center", "td_tableData", 1));

            ht.Controls.Add(row);

            return ht;
        }

        /// <summary>
        /// 添加数据到表格
        /// </summary>
        /// <param name="dtA"></param>
        /// <param name="ht"></param>
        /// <returns></returns>
        private HtmlGenericControl FillDataToHtmlTable(DataTable dtA, HtmlGenericControl ht, string dataCellClass)
        {
            HtmlTableRow row = null;
            foreach (DataRow dr in dtA.Rows)
            {
                row = CreateHTMLRow("", null, "");

                row.Cells.Add(CreateHTMLCell(dr[0].ToString() == "" ? "&nbsp;" : dr[0].ToString(), "border-left-width:2px;border-top-width:0px;border:1px solid;", "center", dataCellClass, 1));
                row.Cells.Add(CreateHTMLCell(dr[1].ToString() == "" ? "&nbsp;" : dr[1].ToString(), "border-top-width:0px;border:1px solid;", "center", dataCellClass, 1));
                row.Cells.Add(CreateHTMLCell(dr[2].ToString() == "" ? "&nbsp;" : dr[2].ToString(), "border-top-width:0px;border:1px solid;", "center", dataCellClass, 1));
                row.Cells.Add(CreateHTMLCell(dr[3].ToString() == "" ? "&nbsp;" : dr[3].ToString(), "border-top-width:0px;border:1px solid;", "center", dataCellClass, 1));

                ht.Controls.Add(row);
            }
            return ht;
        }

        /// <summary>
        /// 添加空数据到表格
        /// </summary>
        /// <param name="rowCount"></param>
        /// <param name="table"></param>
        /// <param name="dataCellClass"></param>
        /// <returns></returns>
        private HtmlGenericControl FillEmptyDataToHtmlTable(int rowCount, HtmlGenericControl table, string dataCellClass)
        {
            HtmlTableRow row = null;

            for (int j = 0; j < rowCount; j++)
            {
                row = CreateHTMLRow("", null, null);
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-left-width:2px;border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;  ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;  ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px; ", "left", dataCellClass, 1));
                //row.Cells.Add(CreateHTMLCell("&nbsp;", " border-top-width:0px;border-right-width:2px; ", "left", dataCellClass, 1));

                table.Controls.Add(row);
            }
            return table;
        }

        /// 获取一页数据
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="pageCount"></param>
        /// <param name="currentPage"></param>
        /// <returns></returns>
        private DataTable GetListDataOfOnePage(DataTable dataTable, int pageCount, int currentPage)
        {
            DataTable returnTable = dataTable.Clone();

            DataRow dr = null;
            int beginCount = (currentPage - 1) * pageCount;
            int endCount = dataTable.Rows.Count;
            for (int i = beginCount; i < endCount && i < currentPage * pageCount; i++)
            {
                dr = dataTable.Rows[i];
                returnTable.ImportRow(dr);
            }
            return returnTable;
        }

        private void FillTableToTbody(HtmlGenericControl table, ref HtmlGenericControl tBody, int allCount, int pageCount, int currentPage)
        {
            HtmlTableCell cell = null;
            HtmlTableRow row = null;
            cell = CreateHTMLCell(null, "width:100%", null, null, 12);
            cell.Controls.Add(table);

            row = CreateHTMLRow(null, null, null);
            row.Cells.Add(cell);
            tBody.Controls.Add(row);
            if (allCount > pageCount && allCount - pageCount * currentPage > 0)
            {
                row = CreateHTMLRow(null, "display:none;page-break-before:always", null);
                tBody.Controls.Add(row);
            }
        }

        protected int AccountValueLenth(string value)
        {
            int valueLenth;
            byte[] array = System.Text.Encoding.Default.GetBytes(value);
            return valueLenth = array.Length;
        }

        #endregion 添加数据

        #region 创建表格

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellClass, int cellCospan)
        {
            HtmlTableCell cell = new HtmlTableCell();
            return cell = CreateHTMLCell(cellText, cellStyle, cellAlign, cellClass, cellCospan, 1);
        }

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellClass, int cellCospan, int cellRowspan)
        {
            return CreateHTMLCell(cellText, cellStyle, cellAlign, null, cellClass, cellCospan, cellRowspan);
        }

        public HtmlTableCell CreateHTMLCell(string cellText, string cellStyle, string cellAlign, string cellValign, string cellClass, int cellCospan, int cellRowspan)
        {
            HtmlTableCell cell = new HtmlTableCell();
            if (cellText != null)
            {
                cell.InnerHtml = Server.HtmlDecode(cellText);
            }
            if (cellStyle != null)
            {
                cell.Attributes.Add("style", cellStyle);
            }
            if (cellCospan > 1)
            {
                cell.ColSpan = cellCospan;
            }
            if (cellAlign != null)
            {
                cell.Align = cellAlign;
            }
            if (cellValign != null)
            {
                cell.VAlign = cellValign;
            }
            if (cellClass != null)
            {
                cell.Attributes.Add("class", cellClass);
            }
            if (cellRowspan > 1)
            {
                cell.RowSpan = cellRowspan;
            }
            return cell;
        }

        public HtmlTableRow CreateHTMLRow(string rowHeight, string rowStyle, string rowClass)
        {
            HtmlTableRow row = new HtmlTableRow();
            if (rowHeight != null)
            {
                row.Height = rowHeight;
            }
            if (rowStyle != null)
            {
                row.Attributes.Add("style", rowStyle);
            }
            if (rowClass != null)
            {
                row.Attributes.Add("class", rowClass);
            }
            return row;
        }

        public HtmlTable CreateHTMLTable(string width, string tableClass)
        {
            return CreateHTMLTable(width, string.Empty, tableClass, "0", "0", "0");
        }

        public HtmlTable CreateHTMLTable(string width, string style, string tableClass)
        {
            return CreateHTMLTable(width, style, tableClass, "0", "0", "0");
        }

        public HtmlTable CreateHTMLTable(string width, string style, string tableClass, string tableBorderWidth, string cellspacingValue, string cellpaddingValue)
        {
            HtmlTable ht = new HtmlTable();
            ht.Attributes.Add("width", width);
            ht.Attributes.Add("style", style);
            ht.Attributes.Add("class", tableClass);
            ht.Attributes.Add("border", tableBorderWidth);
            ht.Attributes.Add("cellspacing", cellspacingValue);
            ht.Attributes.Add("cellpadding", cellpaddingValue);

            return ht;
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string tableClass)
        {
            return CreateHTMLMainTable(width, string.Empty, tableClass, "0", "0", "0");
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string style, string tableClass)
        {
            return CreateHTMLMainTable(width, style, tableClass, "0", "0", "0");
        }

        public HtmlGenericControl CreateHTMLMainTable(string width, string style, string tableClass, string tableBorderWidth, string cellspacingValue, string cellpaddingValue)
        {
            HtmlGenericControl ht = new HtmlGenericControl("table");
            ht.Attributes.Add("width", width);
            ht.Attributes.Add("style", style);
            ht.Attributes.Add("class", tableClass);
            ht.Attributes.Add("border", tableBorderWidth);
            ht.Attributes.Add("cellspacing", cellspacingValue);
            ht.Attributes.Add("cellpadding", cellpaddingValue);

            return ht;
        }

        #endregion 创建表格
    }
}